//
//  LoginViewController.m
//  LogisticsFollow
//
//  Created by JustFei on 2016/12/15.
//  Copyright © 2016年 manridy. All rights reserved.
//

#import "LoginViewController.h"
#import "MainViewController.h"
#import "AFNetworking.h"
#import "UserModel.h"
#import "MBProgressHUD.h"
#import <CoreLocation/CoreLocation.h>

@interface LoginViewController () < CLLocationManagerDelegate >

@property (nonatomic ,strong) MBProgressHUD *hud;
@property (nonatomic,strong)CLLocationManager *locMgr;
@property (nonatomic ,strong) CLLocation *loc;

@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Action
- (IBAction)loginAction:(UIButton *)sender
{
    [self.userNameTextField resignFirstResponder];
    [self.pwdTextField resignFirstResponder];
    if (self.userNameTextField.text.length == 11 && (self.pwdTextField.text.length >= 6 && self.pwdTextField.text.length <= 16)) {
        //判断用户定位服务是否开启
        if ([CLLocationManager locationServicesEnabled]) {
            //开始定位用户的位置
            [self.locMgr startUpdatingLocation];
            [sender setTitle:@"登录中。。。" forState:UIControlStateNormal];
            sender.enabled = NO;
            //每隔多少米定位一次（这里的设置为任何的移动）
            //self.locMgr.distanceFilter=kCLDistanceFilterNone;
            //设置定位的精准度，一般精准度越高，越耗电（这里设置为精准度最高的，适用于导航应用）
            self.locMgr.desiredAccuracy=kCLLocationAccuracyBestForNavigation;
        }else
        {//不能定位用户的位置
            //1.提醒用户检查当前的网络状况
            //2.提醒用户打开定位开关
           UIAlertController *vc = [UIAlertController alertControllerWithTitle:@"提示" message:@"请开启定位服务，否则可能无法登录！" preferredStyle:(UIAlertControllerStyleAlert)];
            UIAlertAction *okAc = [UIAlertAction actionWithTitle:@"去设置" style:UIAlertActionStyleDefault handler:nil];
            [vc addAction:okAc];
            [self presentViewController:vc animated:YES completion:nil];
        }
    }else {
        self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        self.hud.mode = MBProgressHUDModeText;
        self.hud.label.text = @"请输入正确的手机号或密码";
        [self.hud hideAnimated:YES afterDelay:1];
    }
}

- (void)postLoginInfoWithPhone:(NSString *)phoneNumber andPwd:(NSString *)pwdNumber andLocation:(CLLocation *)loc
{
    // 启动系统风火轮
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    
    //服务器给的域名
    NSString *domainStr = kLoginPort;
    
    //假如需要提交给服务器的参数是key＝1,class_id=100
    //创建一个可变字典
    NSMutableDictionary *parametersDic = [NSMutableDictionary dictionary];
    //往字典里面添加需要提交的参数
    [parametersDic setObject:phoneNumber forKey:@"mobile"];
    [parametersDic setObject:pwdNumber forKey:@"password"];
    [parametersDic setObject:[NSNumber numberWithFloat:loc.coordinate.longitude] forKey:@"positionX"];
    [parametersDic setObject:[NSNumber numberWithFloat:loc.coordinate.latitude] forKey:@"positionY"];
    // 获取当前所在的城市名
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    //根据经纬度反向地理编译出地址信息
    [geocoder reverseGeocodeLocation:loc completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        for (CLPlacemark * place in placemarks) {
            //            NSLog(@"国家：%@",place.country);
            //            NSLog(@"城市：%@",place.locality);
            //            NSLog(@"区：%@",place.subLocality);
            //            NSLog(@"街道：%@",place.thoroughfare);
            //            NSLog(@"子街道：%@",place.subThoroughfare);
            NSString *address = [NSString stringWithFormat:@"%@%@%@",place.locality ,place.subLocality ,place.thoroughfare];
            NSLog(@"位置：%@",address);
            [parametersDic setObject:address forKey:@"address"];
        }
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        
        //以post的形式提交，POST的参数就是上面的域名，parameters的参数是一个字典类型，将上面的字典作为它的参数
        [manager POST:domainStr parameters:parametersDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            // 隐藏系统风火轮
            [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
            
            //json解析
            NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
            //转成jsonModel
            UserModel *model = [[UserModel alloc] initWithDictionary:resultDic error:nil ];
            NSLog(@"isSuccess = %d\nmsg = %@\nresult = %@",model.isSuccess ,model.msg ,model.result);
            if (model.isSuccess) {
                ResultModel *resultModel = model.result[0];
                NSString *guid = resultModel.guid;
                [[NSUserDefaults standardUserDefaults] setObject:guid forKey:@"guid"];
                [self doSuccessLogin];
            }else {
                [self doFailLogin];
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            // 解析失败隐藏系统风火轮(可以打印error.userInfo查看错误信息)
            [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
            [self doFailLogin];
        }];
    }];
    
    
}

- (void)doSuccessLogin
{
    [self.loginButton setTitle:@"登录成功" forState:UIControlStateNormal];
    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"logined"];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        MainViewController *vc = [[MainViewController alloc] init];
        [self presentViewController:[[UINavigationController alloc] initWithRootViewController:vc] animated:YES completion:nil];
    });
}

- (void)doFailLogin
{
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"logined"];
    [self.loginButton setTitle:@"登录失败，请重试" forState:UIControlStateNormal];
    self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    self.hud.mode = MBProgressHUDModeText;
    self.hud.label.text = @"请输入正确的手机号或密码";
    [self.hud hideAnimated:YES afterDelay:2];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.loginButton setTitle:@"登录" forState:UIControlStateNormal];
        self.loginButton.enabled = YES;
        
    });
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.userNameTextField resignFirstResponder];
    [self.pwdTextField resignFirstResponder];
}

#pragma mark - CLLocationManagerDelegate
/**
 *  当定位到用户的位置时，就会调用（调用的频率比较频繁）
 */
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    //locations数组里边存放的是CLLocation对象，一个CLLocation对象就代表着一个位置
    self.loc = [locations firstObject];
    if (self.loc) {
        [self postLoginInfoWithPhone:self.userNameTextField.text andPwd:self.pwdTextField.text andLocation:self.loc];
    }
    
    //维度：loc.coordinate.latitude
    //经度：loc.coordinate.longitude
    NSLog(@"纬度=%f，经度=%f",self.loc.coordinate.latitude,self.loc.coordinate.longitude);
    NSLog(@"%ld",locations.count);
    
    //停止更新位置（如果定位服务不需要实时更新的话，那么应该停止位置的更新）
    [self.locMgr stopUpdatingLocation];
}

#pragma mark - 懒加载
-(CLLocationManager *)locMgr
{
    if (_locMgr==nil) {
        //1.创建位置管理器（定位用户的位置）
        _locMgr=[[CLLocationManager alloc]init];
        //
#ifdef __IPHONE_8_0
        if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
            [_locMgr requestAlwaysAuthorization];
        }
#endif
        
        //2.设置代理
        _locMgr.delegate=self;
    }
    return _locMgr;
}

@end
